package com.itheima.behavior.server.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ReadBehaviorDTO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.mess.app.NewBehaviorDTO;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.common.user.pojo.ApUser;
import com.itheima.behavior.server.ApBehaviorEntryService;
import com.itheima.behavior.server.ApReadBehaviorService;
import com.itheima.common.constants.article.HotArticleConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {

        ApUser user = AppThreadLocalUtils.getUser();

        ApBehaviorEntry entry = new ApBehaviorEntry();
        if (user==null){//未登录状态 根据设备id查询行为主体
             entry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(dto.getEquipmentId())), ApBehaviorEntry.class);
            if (entry==null){
                entry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
            }
        }else {
            //登录状态根据userid查询行为主体
            Integer userId = user.getId();
            entry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId)), ApBehaviorEntry.class);
            if (entry==null){
                entry=apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
            }
        }
        //判断阅读行为是否存在
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(entry.getId()).and("articleId").is(dto.getArticleId())), ApReadBehavior.class);
        if (apReadBehavior==null){//不存在创建
            ApReadBehavior readBehavior = new ApReadBehavior();
            readBehavior.setCreatedTime(new Date());
            readBehavior.setCount((short)1);
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setEntryId(entry.getId());
            ApReadBehavior save = mongoTemplate.save(readBehavior);
        }else {
             //存在则修改
            Update update = new Update();
            update.set("updatedTime",new Date()).set("count",(short)(apReadBehavior.getCount()+1));
            mongoTemplate.updateMulti(Query.query(Criteria.where("entryId").is(entry.getId()).and("articleId").is(dto.getArticleId())),update,ApReadBehavior.class);
        }
        //阅读行为后发送mq
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("点赞行为 发送消息 ==>{}", JSON.toJSONString(mess));

        return ResponseResult.okResult();
    }

}
